package com.aiden.app.common.widget.glide

import android.content.Context
import android.graphics.*
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.security.MessageDigest

/**
 * Glide原型变换
 *
 * @author yanggeng
 * @date 2019/1/24 下午1:52
 */
class GlideCircleTransform(var context: Context) : BitmapTransformation() {

    private val ID = "com.dahu.app.common.widget.glide.GlideCircleTransform"

    private var size: Int = 0

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(ID.toByteArray(Key.CHARSET))
    }

    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
        return cropCircle(pool, toTransform)
    }

    private fun cropCircle(pool: BitmapPool, source: Bitmap): Bitmap {
        val minSize = Math.min(source.height, source.width)
        this.size = minSize
        val x = (source.width - minSize) / 2
        val y = (source.height - minSize) / 2

        val squared = Bitmap.createBitmap(source, x, y, minSize, minSize)

        val result = pool.get(minSize, minSize, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(result)
        val paint = Paint()
        paint.shader = BitmapShader(squared, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        paint.isAntiAlias = true
        val r = minSize / 2f
        canvas.drawCircle(r, r, r, paint)
        return result
    }

    override fun equals(other: Any?): Boolean {
        if (other is GlideCircleTransform) {
            return this === other
        }
        return false
    }

    override fun hashCode(): Int {
        return ID.hashCode()
    }
}